package ksj.common.tasks.executor.rabbitmq;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import ksj.common.utils.net.Status;
import ksj.common.web.BaseWebService;

@Controller
@RequestMapping("/rabbitmq/executor")
@EntityScan(basePackages = { "bean" })
public class RabbitMQTaskExecutor extends BaseWebService {
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	@RequestMapping(path = "/publishMessage", headers = "Content-Type=application/x-www-form-urlencoded", method = RequestMethod.POST)
	public @ResponseBody Response publishMessage(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("asdasd");
		try {
			String host = request.getParameter("host");
			int portNumber = Integer.parseInt(request.getParameter("portNumber"));
			String queueName = request.getParameter("queueName");
			String userName = request.getParameter("userName");
			String routingKey = request.getParameter("routingKey");
			String password = request.getParameter("password");
			String message = request.getParameter("message");
			String virtualHost = request.getParameter("virtualHost");
			System.out.println("message published!!");

			ConnectionFactory factory = new ConnectionFactory();
			if (virtualHost != null && !("").equals(virtualHost)) {
				factory.setUri(
						"amqp://" + userName + ":" + password + "@" + host + ":" + portNumber + "/" + virtualHost);
			} else {
				factory.setUri("amqp://" + userName + ":" + password + "@" + host + ":" + portNumber);
			}

			Connection connection = factory.newConnection();
			Channel channel = connection.createChannel();

			// channel.basicPublish(queueName, "", null, message.getBytes());
			channel.basicPublish(queueName, routingKey, null, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");
			channel.close();

			System.out.println("end");
			List<String> arraylilst = new ArrayList<>();
			arraylilst.add("Success!");

			// return arraylilst;
			return createResponse(Status.RESPONSE_INFO_SUCCESS, Status.RESPONSE_MESSAGE_INFO_SUCCESS, arraylilst);
		} catch (Exception e) {
			e.printStackTrace();
			return createResponse(Status.RESPONSE_INFO_FAILURE, Status.RESPONSE_MESSAGE_INFO_FAILURE, null);
		}
	}

}